package com.permission.utils;

import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.permission.constant.Constants;
import com.permission.entity.SysOperationLogEntity;
import com.permission.handler.SystemLog;
import com.permission.message.StandardResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @desc:
 * @projectName: permission-parent
 * @author: xhs
 * @date: 2021/12/31 15:34
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class SystemLogUtil {
    @Autowired
    private static SystemLog systemLog;

    @Autowired
    public void setSpApilogMapper(SystemLog systemLog) {
        SystemLogUtil.systemLog = systemLog;
    }

    /**
     * 请求开始时调用，开始计时
     */
    public static void startRequest() {
        HttpServletRequest request = SpringMVCUtil.getRequest();
        String ip = CommonIpAddressUtil.getIp(request);
        String address = CommonIpAddressUtil.getCityInfo(ip);
        SysOperationLogEntity operationLogEntity = SysOperationLogEntity.builder()
                .requestApi(request.getRequestURI())
                .requestType(request.getMethod())
                .requestParame("{}")
                .requestToken(StpUtil.getTokenValue())
                .creator(StpUtil.getLoginIdAsString())
                .creatorIp(ip)
                .creatorAddress(address)
                .startTime(new Date())
                .build();
        request.setAttribute(Constants.APILOG_OBJ_SAVE_KEY, operationLogEntity);
    }

    /**
     * 请求结束时调用，结束计时
     */
    public static void endRequest(StandardResponse standardResponse) {
        HttpServletRequest request = SpringMVCUtil.getRequest();
        SysOperationLogEntity attribute = (SysOperationLogEntity) request.getAttribute(Constants.APILOG_OBJ_SAVE_KEY);
        if (attribute == null) {
            SystemLogUtil.startRequest();
            attribute = (SysOperationLogEntity) request.getAttribute(Constants.APILOG_OBJ_SAVE_KEY);
        }
        // 保存数据库
        try {
            // 开始结束计时
            attribute.setResCode(standardResponse.getStatus());
            attribute.setResMsg(standardResponse.getMsg());
            attribute.setResJson(new ObjectMapper().writeValueAsString(standardResponse));
            attribute.setEndTime(new Date());
            attribute.setCostTime((int) (attribute.getEndTime().getTime() - attribute.getStartTime().getTime()));

            // res 字符串过长时禁止写入
            if (attribute.getResJson().length() > 50000) {
                attribute.setResJson("{\"msg\": \"数据过长，无法写入 (length=" + attribute.getResJson().length() + ")\"}");
            }

            log.info("本次请求耗时：" + ((attribute.getCostTime() + 0.0) / 1000) + "s, 返回：" + attribute.getResJson());
            systemLog.systemLog(attribute);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
